/**
 * Chengzai.com Inc.
 * Copyright (c) 2016-2017 All Rights Reserved.
 */
package com.auxgroup.hr.front.service.configure;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.alibaba.fastjson.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;

/**
 * RestTemplate配置
 *
 */
@Configuration
public class RestTemplateConfig {

    @Autowired
    private Environment env;

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {

        RestTemplate restTemplate = new RestTemplate(factory);

        //使用utf-8编码集的conver替换默认的conver（默认的conver的编码集为"ISO-8859-1"）
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        FastJsonHttpMessageConverter fjConverter = new FastJsonHttpMessageConverter();
        fjConverter.getFastJsonConfig().setCharset(Charset.forName("GB2312"));
        messageConverters.add(fjConverter);
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(Integer.valueOf(env.getProperty("rest.readTimeout")));
        factory.setConnectTimeout(Integer.valueOf(env.getProperty("rest.connectTimeout")));
        return factory;
    }


    /**
     * Getter method for property <tt>env</tt>.
     *
     * @return property value of env
     */
    public Environment getEnv() {
        return env;
    }

    /**
     * Setter method for property <tt>counterType</tt>.
     *
     * @param env value to be assigned to property env
     */
    public void setEnv(Environment env) {
        this.env = env;
    }
}
